class Revision < ActiveRecord::Base
	belongs_to :page
	belongs_to :user
	has_many :comments
	
	validates_presence_of :content
	before_save :generate_wikified_content

	# get the revision number as displayed on the page
	def rid
		return 1 if self.page.nil?

		revs = self.page.index_revisions
		n = 0
		until n >= revs.length || revs[n] == self
			n += 1
		end
		revs.length - n
	end

	def earliest?
		return true if self.page.nil?
		self.id == self.page.index_revisions.last.id
	end

	def latest?
		return true if self.page.nil?
		self.id == self.page.index_revisions.first.id
	end

	def only?
		latest? && earliest?
	end
	
	def to_s
	  # for compability with old data, generate and save wikified content if it doesnt already exist
	  if self.wikified_content.blank?
	    generate_wikified_content
	    self.save
    end
    self.wikified_content.linkify
	end
	
	private
	
	# materialize the wikified version of the content in db, so it doesn't get regenerated for each page view
	def generate_wikified_content
	  self.wikified_content = self.content.wikify({ :skip_links => true })
	end
end
